<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/26
 * Time: 17:31
 */
use Workerman\Worker;
require_once   '../Autoloader.php';

// 创建一个Worker监听2346端口，使用websocket协议通讯
$ws_worker = new Worker("websocket://0.0.0.0:2000");

// 启动4个进程对外提供服务
$ws_worker->count = 4;

$ws_worker->onConnect = function($connection)
{
    echo $connection->id;
};

// 当收到客户端发来的数据后返回hello $data给客户端
/**
 * @param $connection
 * @param $data
 */
$ws_worker->onMessage = function($connection, $data)
{


    $connection->send('hello ' . $data);
};

// 开启多少个进程运行定时任务，注意业务是否在多进程有并发问题

$ws_worker->onWorkerStart = function($worker)
{
    // 每2.5秒执行一次
    $time_interval = 30;
    \Workerman\Lib\Timer::add($time_interval, function()use($worker)
    {
        if($worker->connections[2]){
            $worker->connections[2]->send('hello*************2');
        }

        foreach($worker->connections as $connection)
        {
            //$connection->send($connection->user);
        }
    });
};

$ws_worker->onClose = function($connection)
{
    echo "connection closed\n";
};
// 运行worker
Worker::runAll();